package com.lemon.smartsafetynew.ui.activity.hidden;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;

import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafetynew.ui.activity.base.SwipeBackActivity;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.utils.common.LemonFileHelper;
import com.lemon.smartsafetynew.entity.event.common.ViewEvent;
import com.lemon.smartsafetynew.entity.event.hidden.HiddenMediaEvent;
import com.lemon.smartsafetynew.entity.hidden.SafeHiddenDownloadVo;
import com.lemon.smartsafetynew.net.services.SafeHiddenServices;
import com.lemon.smartsafetynew.ui.fragment.hidden.SafeHiddenProcessTabOneContentFragment;
import com.lemon.smartsafetynew.ui.fragment.hidden.SafeHiddenProcessTabOneFragment;
import com.lemon.smartsafetynew.ui.fragment.hidden.SafeHiddenProcessTabTwoFragment;
import com.lemon.smartsafetynew.util.common.UrlFormatUtils;
import com.lemon.smartsafetynew.util.constants.KeyConstants;


import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import cn.finalteam.galleryfinal.model.PhotoInfo;

/**
 * Created by Andrew on 2017/9/10.
 */

public class SafeHiddenInfoActivity extends SwipeBackActivity {

    @Bind(R.id.tabLayout)
    TabLayout tabLayout;
    @Bind(R.id.viewPager)
    ViewPager viewPager;

    private static SafeHiddenDownloadVo safeHiddenDownloadVo;

    private HiddenInfoViewpagerAdapter viewpagerAdapter;

    @Override
    protected void getBundleArgs() {
        super.getBundleArgs();

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            if (bundle.containsKey(KeyConstants.KEY_SAFE_HIDDEN_DOWNLOAD_VO)) {
                safeHiddenDownloadVo = (SafeHiddenDownloadVo) bundle.getSerializable(KeyConstants.KEY_SAFE_HIDDEN_DOWNLOAD_VO);
            }
        }
    }

    @Override
    protected void initTitle() {
        this.setTitle("隐患信息");
    }

    @Override
    protected void callFinish() {
        AppService.getBus().post(new ViewEvent(SafeHiddenInfoActivity.class.getName()));
        AppManager.getAppManager().finishActivity(this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_viewpage_tab_layout;
    }

    @Override
    protected void initViews() {
        super.initViews();

        // ======= 该变指示栏的长度 =======
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                setIndicator(tabLayout, 10, 10); //左右各缩进5dp
            }
        });

        initViewPager();
    }

    /**
     * 初始化ViewPager
     */
    private void initViewPager() {
        viewpagerAdapter = new HiddenInfoViewpagerAdapter(getSupportFragmentManager());
        viewPager.setAdapter(viewpagerAdapter);
        //viewPager.setPageTransformer(true, new ZoomOutSlideTransformer());
        tabLayout.setupWithViewPager(viewPager);
    }

    private class HiddenInfoViewpagerAdapter extends FragmentStatePagerAdapter {

        public HiddenInfoViewpagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    return SafeHiddenProcessTabOneFragment.newInstance(safeHiddenDownloadVo);
                case 1:
                    return SafeHiddenProcessTabTwoFragment.newInstance(safeHiddenDownloadVo);
                default:
                    return SafeHiddenProcessTabOneFragment.newInstance(safeHiddenDownloadVo);
            }
        }

        @Override
        public int getCount() {
            return 2;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return getString(R.string.hidden_info_tab_1);
                case 1:
                    return getString(R.string.hidden_info_tab_2);
            }
            return null;
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(ViewEvent event) {
        if (SafeHiddenRectifyAndReformActivity.class.getName().equals(event.getTag())) {
            getHiddenDangerDto();
        } else if (SafeHiddenReviewActivity.class.getName().equals(event.getTag())) {
            getHiddenDangerDto();
        } else if (SafeHiddenProcessDetailActivity.class.getName().equals(event.getTag())) {
            getHiddenDangerDto();
        } else if (SafeHiddenDocumentActivity.class.getName().equals(event.getTag())) {
            getHiddenDangerDto();
        }
    }

    /**
     * 更新Hidden Danger
     */
    private void getHiddenDangerDto() {

        LemonRequestParams params = new LemonRequestParams("");
        params.put("danger_id", safeHiddenDownloadVo.getId());

        SafeHiddenServices
                .init()
                .getSafeHiddenDto(params);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(HttpCallbackEvent event) {
        if (KeyConstants.URL_GET_SAFE_HIDDEN.equals(event.getTag())) {                               //获取隐患信息
            if (HandlerCallback.HttpFlow.START == event.getHttpFlow()) {
                mHUDUtil.showHUD();
            } else if (HandlerCallback.HttpFlow.FINISH == event.getHttpFlow()) {
                mHUDUtil.hidden();
                if (Constants.Result.SUCCESS == event.getEventResult()) {

                    if (event.getObj() instanceof SafeHiddenDownloadVo) {
                        safeHiddenDownloadVo = (SafeHiddenDownloadVo) event.getObj();
                        initViewPager();
                        viewPager.setCurrentItem(1); //暂时只需要显示第二页
                    }

                } else if (Constants.Result.ERROR == event.getEventResult()) {
                    mHUDUtil.showErrorTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            //当获取隐患信息出现问题，退出本页面，返回上级
                            callFinish();
                        }
                    });
                }
            }
        }
    }

    /**
     * 显示图片和音频详情
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMediaEvent(HiddenMediaEvent event) {

        if (SafeHiddenProcessTabOneContentFragment.class.getName().equals(event.getTag())) {

            String url = event.getUrls().get(event.getPosition());

            if (LemonFileHelper.isImageUrl(url)) {
                List<String> urls = event.getUrls();
                List<PhotoInfo> photos = new ArrayList<>();

                int j = 0;
                int currentItem = 0;
                for (int i = 0; i < urls.size(); i++) {
                    if (LemonFileHelper.isImageUrl(urls.get(i))) {

                        if (url.equals(urls.get(i))) {
                            currentItem = j;
                        }

                        PhotoInfo photoInfo = new PhotoInfo();
                        photoInfo.setPhotoId(j);
                        photoInfo.setPhotoPath(UrlFormatUtils.formatFiles(urls.get(i)));
                        photos.add(photoInfo);
                        j++;
                    }
                }

                if (photos != null && photos.size() != 0) {
                    UIHelper.showPhotoView(this, photos, currentItem);
                }
            } else if (LemonFileHelper.isVoiceUrl(url)) {
                playVoice(UrlFormatUtils.formatFiles(url));
            }

        }
    }

}
